package com.itg.vms.servlet;

import com.alibaba.fastjson.JSONObject;
import com.itg.vms.entity.User;
import com.itg.vms.service.UserService;
import com.itg.vms.service.impl.UserServiceImpl;
import com.itg.vms.util.StringUtils;

import com.itg.vms.util.MD5Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/user")
public class UserServlet extends BaseServlet {
    //创建业务层对象
    UserService userService = new UserServiceImpl();

    /**
     * 管理员或者用户自主更新个人信息的接口（不是由管理员来修改普通的用户信息）
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void updateAdminAndUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前台信息
        String nickName = req.getParameter("nickname");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String remark = req.getParameter("remark");
        String username = getUsername(req, resp);
        //封装user对象
        User user = new User();
        user.setNickName(nickName);
        user.setPhoneNumber(phone);
        user.setEmail(email);
        user.setRemark(remark);
        user.setUserName(username);

        //调用业务层更新个人信息方法
        boolean flag = userService.updateAdminAndUserInfo(user);
        if (flag) {
            //资料修改成功
            resp.getWriter().write(success("保存成功"));
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
            resp.getWriter().write(error("保存失败，服务器开小差了......"));
        }

    }

    /**
     * 后台添加用户信息
     */
    public boolean addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //接收提交的值
        String user_name = req.getParameter("user_name");
        String nick_name = req.getParameter("nick_name");
        String user_type = req.getParameter("user_type");
        String email = req.getParameter("email");
        String phonenumber = req.getParameter("phonenumber");
        String gender = req.getParameter("gender");
        String password = MD5Utils.md5(req.getParameter("password"));
        String status = req.getParameter("status");

        User user = new User(user_name, nick_name, user_type, email, phonenumber, gender, password, status);
        user.setCreateBy(getUsername(req, resp));

        //调用userService方法
        boolean flag = userService.addUser(user);
        if (flag) {
            resp.getWriter().write(success("添加成功"));
        } else {
            resp.getWriter().write(error());
        }
        return flag;

    }

    /**
     * 修改用户相关信息
     *
     * @param req
     * @param resp
     * @return
     */
    public boolean UpdateUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //String user_id = req.getParameter("user_id");
        String user_name = req.getParameter("user_name");
        String nick_name = req.getParameter("nick_name");
        String user_type = req.getParameter("user_type");
        String email = req.getParameter("email");
        String phonenumber = req.getParameter("phonenumber");
        String gender = req.getParameter("gender");
        String status = req.getParameter("status");

        boolean i = userService.UpdateUserById(user_name, nick_name, user_type, email, phonenumber, gender, status, getUsername(req, resp));

        if (i) {
            resp.getWriter().write(success("修改成功"));
        } else {
            resp.getWriter().write(error());
        }
        return i;
    }

    /**
     * 删除用户
     */
    public void deleteUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String user_id = req.getParameter("user_id");
        int i = userService.deleteUserById(user_id, getUsername(req, resp));
        resp.getWriter().write(toAjax(i));
    }

    /**
     * 根据用户Id，用户名,用户昵称，手机号码查询用户
     *
     * @param req
     * @param resp
     * @return
     */
    public void selectUserByName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String user_id = req.getParameter("user_id");
        String user_name = req.getParameter("user_name");
        String nick_name = req.getParameter("nick_name");
        String phonenumber = req.getParameter("phonenumber");
        List<User> list = userService.selectUserByName(user_id, user_name, nick_name, phonenumber);
        if (list != null) {
            resp.getWriter().write(success(list, Long.valueOf(list.size())));
        } else {
            resp.getWriter().write(error());
        }
    }

    /**
     * 分页查询用户
     *
     * @author zjzaki
     */
    public void selectAllUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //得到请求参数
        String page = req.getParameter("page");
        Integer currentPage = Integer.valueOf(page);
        String limit = req.getParameter("limit");
        Integer pageSize = Integer.valueOf(limit);

        //当前页面数减1，mysql分页从第0也开始
        currentPage = currentPage - 1;
        //调用业务层方法查询数据
        List<User> users = userService.selectAllUser(currentPage, pageSize);
        //得到user表的总记录数
        Long allUseSize = userService.getAllUseSize();
        //判断这个列表是否为null，为null查询失败
        if (StringUtils.isNotNull(users)) {
            resp.getWriter().write(success(users, allUseSize));
        } else {
            resp.getWriter().write(error("查询失败"));
        }
    }

    /**
     * 修改密码
     */
    public void updateUserPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前台传来的数据
        String old_password = req.getParameter("old_password");
        String new_password = req.getParameter("new_password");
        String again_password = req.getParameter("again_password");
        String NewPassword = null;
        if (new_password.equals(again_password)) {
            NewPassword = again_password;
        }

        //调用业务层方法
        boolean b = userService.updatePassword(NewPassword, getUsername(req, resp));
        if (b) {
            System.out.println("修改密码成功");
            req.getSession().removeAttribute("loginUser");
            resp.getWriter().write(success("修改密码成功,请重新登录"));
        } else {
            System.out.println("服务器开小差了。。");
            resp.getWriter().write(error("服务器开小差了..请稍后再试"));
        }
    }

    /**
     * 获取编辑框中的数据
     *
     * @param req
     * @param resp
     * @return
     */
    public void GeteditUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String user_id = req.getParameter("id");
        User user = userService.GeteditUserById(user_id);
        if (user != null) {
            resp.getWriter().write(success(user));
        } else {
            resp.getWriter().write(error());
        }
    }

    /**
     *  修改用户状态
     */
    public void updateUserStatus(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String userId = req.getParameter("userId");
        String status = req.getParameter("status");

        int i = userService.updateUserStatus(userId, status);

        resp.getWriter().write(toAjax(i));
    }
}
